import React, { Component } from 'react'
import { connect } from 'dva';
import Link from 'umi/link';
import { Form, Input, Button, notification, message, Icon, Radio, Select, Checkbox } from 'antd';
import { FormComponentProps } from "antd/lib/form/Form";
import { DICT } from '@/pages/data/report_template_question/enum';
import { routerRedux } from 'dva/router';
import { createProblem, updateProblem } from '../problemService.js';

const RadioGroup = Radio.Group;
const CheckboxGroup = Checkbox.Group;
const { Option } = Select;

interface Props extends FormComponentProps {
  dispatch?: Function,
  data?: {
    type: string,
  },
  dict?: any
}

@connect(({ report_template_question }) => ({
  dict: report_template_question.dict
}))

class ProblemForm extends Component<Props, any> {
  constructor(props) {
    super(props);
  }
  state = {
    confirmDirty: false,
    autoCompleteResult: [],
    isNew: true,
    problemList: [],
    value: 0,
    checkValue: null,
    isSelected: false,
    selectValue: null,
    params: {
      id: '',
      name: '',
      type: null,
      checkType: '2',
      item: []
    },
    updateData: {
    },
    updateCheck: {
    },
    defaultCheck: [],
    defaultName: '',
    id: ''
  };

  DefaultInput = (data, form, typeData, type) => {
    this.setState({
      [typeData]: data,
      problemList: data.itemList ? data.itemList : [],
      selectValue: data ? data.type : '',
      defaultName: data ? data.name : '',
      id: data ? data.id : ''
    }, () => {
      if(this.state.problemList.length > 0) {
        if(this.state.selectValue === '2') {
          this.state.problemList.forEach((item, index) => {
            if(item.isDefault === '1') {
              this.setState({
                value: index
              })
            }
          });
        }
        if(this.state.selectValue !== '1') {
          let names = {};
          this.state.problemList.forEach((item, index) => {
            names[type + index] = item.context;
          });
          form.setFieldsValue(names)
        }
        if(this.state.selectValue === '3') {
          this.state.problemList.forEach((item, index) => {
            if(item.isDefault === '1') {
              this.state.defaultCheck.push(index)
            }
          });
          this.setState({
            defaultCheck: this.state.defaultCheck
          })
        }
      }
    });
  };

  componentWillMount() {
    message.loading('', 0.5);
    const { data = {name: '', type: '', itemList: []}, dispatch, form } = this.props;
    dispatch({
      type: 'report_template_question/queryDict',
      payload: {
        keyList: DICT
      }
    });
    if(data && !data.type) {
      return;
    }
    if(data && data.type === '1') {
      this.setState({
        updateData: data,
        selectValue: data ? data.type : '',
        defaultName: data ? data['name'] : '',
        id: data ? data['id'] : ''
      });
      return;
    }
    if(data && data.type === '2') {
      this.DefaultInput(data, form, 'updateData', 'option');
    }
    if(data && data.type === '3') {
      this.DefaultInput(data, form, 'updateCheck', 'check');
    }
    this.setState({
      isSelected: true
    })
  }

  handleSubmit = (e) => {
    e.preventDefault();
    const { form, dispatch } = this.props;
    this.state.params.name = document.getElementById('problem')['value'].trim();
    if(!this.state.params.name) {
      message.warning('请填写问题名称', 1.5);
      return;
    }
    if(!this.state.selectValue) {
      message.warning('请选择问题类型', 1.5);
      return;
    }
    message.loading('', 0.5);
    let status = true;
    switch(this.state.selectValue) {
      case '1':
        this.state.params.type = '1';
        break;
      case '2':
        this.state.params.type = '2';
        this.state.params.item = [];
        let isAllOption = true;
        let optionInputList = document.querySelectorAll('.option_input');
        optionInputList.forEach(item => {
          if(!item['value'].trim()) {
            isAllOption = false;
          }
        });
        if(isAllOption) {
          if(this.state.problemList.length === 0) {
            message.warning('请添加选项');
            return;
          }
          form.validateFields((err, values) => {
            if(this.state.problemList.length < 2) {
              message.warning('至少创建两个选项', 1.5);
              status = false;
            }
            this.state.problemList.forEach((o_item, index) => {
              this.state.params.item.push({
                context: values['option' + index],
                orderNo: index,
                isDefault: index === +this.state.value ? '1' : '0'
              })
            });
          });
        }else {
          message.warning('请将问题填写完整', 1.5);
          status = false;
        }
        break;
      case '3':
        this.state.params.type = '3';
        this.state.params.item = [];
        let isAllCheck = true;
        let checkInputList = document.querySelectorAll('.check_input');
        checkInputList.forEach(item => {
          if(!item['value'].trim()) {
            isAllCheck = false;
          }
        });
        if(isAllCheck) {
          if(this.state.problemList.length === 0) {
            message.warning('请添加选项');
            return;
          }
          form.validateFields((err, values) => {
            if(this.state.problemList.length < 2) {
              message.warning('至少创建两个选项', 1.5);
              status = false;
              return;
            }
            if(!this.state.checkValue) {
              message.warning('请选择选项');
              status = false;
              return;
            }
            this.state.problemList.forEach((c_item, index) => {
              this.state.params.item.push({
                context: values['check' + index],
                orderNo: index,
                isDefault: '0'
              })
            });
            if(Array.isArray(this.state.checkValue)) {
              this.state.checkValue.forEach(c_item => {
                this.state.params.item[c_item].isDefault = '1';
              });
            }else {
              if(this.state.defaultCheck.length > 0) {
                this.state.defaultCheck.forEach(c_item => {
                  this.state.params.item[c_item].isDefault = '1';
                });
              }
            }
          });
        }else {
          message.warning('请将问题填写完整', 1.5);
          status = false;
        }
        break;
    }
    if(!status) {
      return;
    }
    if(!!this.state.id) {
      this.state.params.id = this.state.id;
      updateProblem(this.state.params).then((data) => {
        if(data === undefined) {
          return;
        }
        dispatch(routerRedux.push('/data/report_template_question'));
      });
    }else {
      createProblem(this.state.params).then((data) => {
        if(data === undefined) {
          return;
        }
        dispatch(routerRedux.push('/data/report_template_question'));
      });
    }
  };

  addProblem = () => {
    this.state.problemList.push(1);
    this.setState({
      problemList: this.state.problemList
    })
  };
  onChangeRedio = (e) => {
    this.setState({
      value: e.target.value,
    });
  };
  changeCheck = (value) => {
    this.state.checkValue = value;
  };
  removeCheck(index) {
    const { form } = this.props;
    let names = {};
    this.state.problemList.splice(index, 1);
    if(this.state.selectValue === '2' && !!this.state.id && this.state.problemList.length > 0) {
      this.state.problemList.forEach((item, index) => {
        names['option' + index] = item.context;
      });
    }
    if(this.state.selectValue === '3' && !!this.state.id && this.state.problemList.length > 0) {
      this.state.problemList.forEach((item, index) => {
        names['check' + index] = item.context;
      });
    }
    form.setFieldsValue(names);
    this.state.problemList.forEach((item, index) => {
      if(item.isDefault === '1') {
        this.state.defaultCheck.push(index)
      }
    });
    this.setState({
      problemList: this.state.problemList,
      defaultCheck: this.state.defaultCheck
    })
  };
  removeOpton = (index) => {
    this.state.problemList.splice(index, 1);
    this.setState({
      problemList: this.state.problemList
    }, () => {
      this.setState({
        value: 0
      })
    })
  };
  setProblemType = (value) => {
    if(+value > 1) {
      this.setState({
        isSelected: true,
        selectValue: value,
        problemList: []
      })
    }else {
      this.setState({
        isSelected: false,
        selectValue: value,
        problemList: []
      })
    }
  };
  getOption = (data) => {
    const children = [];
    let { entries } = Object;
    for (let [key, value] of entries(data)) {
      children.push(<Option key={key}>{value}</Option>);
    }
    return children;
  };

  render() {
    const { form, data, dict } = this.props;
    const { getFieldDecorator } = form;
    const addFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 12,
          offset: 0,
        },
        sm: {
          span: 8,
          offset: 1,
        },
      },
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 12,
          offset: 0,
        },
        sm: {
          span: 8,
          offset: 2,
        },
      },
    };
    return (
      <div>
        <div className="problem-head" style={{'display': 'flex'}}>
          <div style={{'width': '40%', 'marginLeft': '60px'}}>
            <label htmlFor="problem">问题：</label>
            <Input id="problem" style={{'width': '80%'}} placeholder="请输入想要新增的问题" defaultValue={this.state.defaultName ? this.state.defaultName : ''}/>
          </div>
          <div style={{'width': '50%', 'marginLeft': '20px'}}>
            <label htmlFor="type">问题类型：</label>
            <Select
              style={{ width: '60%' }}
              placeholder="请选择"
              onChange={this.setProblemType}
              defaultValue={this.state.selectValue ? this.state.selectValue : ''}
            >
              { dict['report.question.type'] ? this.getOption(dict['report.question.type']) : null }
            </Select>
          </div>
        </div>
        <Form onSubmit={this.handleSubmit}>
          {
            <div className="problem-list" style={{'marginLeft': '60px'}}>
              <RadioGroup onChange={this.onChangeRedio} value={this.state.value} style={{'width': '55%'}} className={this.state.selectValue !== '2' ? 'none' : ''}>
                {
                  this.state.problemList.map((item, index) => (
                    <div style={{'margin': '20px 0'}} key={index}>
                      <label htmlFor={'p' + index}>{'问题选项' + (index + 1) + '：'}</label>
                      <Radio name={'p' + index} value={index} style={{'width': '70%'}}>
                        {
                          getFieldDecorator('option' + index, {
                            rules: [{ message: '选项' + index }],
                          })(
                            <Input placeholder='问题选项并在选择您认可的正确选项，默认为第选项第一个' className="option_input"/>
                          )
                        }
                        <span style={{'marginLeft': '15px', 'cursor': 'pointer'}}>
                        <Icon type="minus" onClick={(index) => {this.removeOpton(index)}}/>
                      </span>
                      </Radio>
                    </div>
                  ))
                }
              </RadioGroup>
              <CheckboxGroup
                onChange={this.changeCheck}
                style={{'width': '55%'}}
                className={this.state.selectValue !== '3' ? 'none' : ''}
                defaultValue={this.state.defaultCheck}
              >
                {
                  this.state.problemList.map((item, index) => (
                    <div style={{'margin': '20px 0'}} key={index}>
                      <label htmlFor={'p' + index}>{'问题选项' + (index + 1) + '：'}</label>
                      <Checkbox name={'p' + index} value={index} style={{'marginRight': '15px'}}></Checkbox>
                        {
                          getFieldDecorator('check' + index, {
                            rules: [{ message: '选项' + index }],
                          })(
                            <Input placeholder='问题选项并在选择您认可的正确选项，默认为第选项第一个' style={{'width': '70%'}} className="check_input"/>
                          )
                        }
                        <span style={{'marginLeft': '15px', 'cursor': 'pointer'}}>
                          <Icon type="minus" onClick={this.removeCheck.bind(this, index)}/>
                        </span>
                    </div>
                  ))
                }
              </CheckboxGroup>
            </div>
          }
          <Form.Item {...addFormItemLayout} className={this.state.isSelected ? '' : 'none'} style={{'marginTop': '20px'}}>
            <Button type="dashed" icon='plus' style={{'marginLeft': '15px'}} onClick={() => {this.addProblem()}}>新增选项</Button>
          </Form.Item>
          <Form.Item {...tailFormItemLayout} style={{'marginTop': '40px'}}>
            <Button type="primary" htmlType="submit">{ !!data ? '修改' : '确定' }</Button>
            <Link to='/data/report_template_question'>
              <Button style={{ marginLeft: '5%' }}>返回</Button>
            </Link>
          </Form.Item>
        </Form>
      </div>
    );
  }
}

const FormList = Form.create()(ProblemForm);
export default FormList;
